package com.taptech.doufu.ui.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.ui.adapter.WholeCartoonDetailAdapter;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.bean.ImageBean;
import com.taptech.doufu.bean.CollectExistGsonBean;
import com.taptech.doufu.bean.base.ResponseBaseBean;
import com.taptech.doufu.bean.cartoon.CartoonBean;
import com.taptech.doufu.bean.cartoon.CartoonDetail;
import com.taptech.doufu.bean.cartoon.CartoonDetailGsonBean;
import com.taptech.doufu.bean.cartoon.CartoonReadTicketBean;
import com.taptech.doufu.bean.cartoon.CartoonReadTicketGsonBean;
import com.taptech.doufu.bean.cartoon.CartoonSectionInfo;
import com.taptech.doufu.bean.cartoon.PayCartoonBean;
import com.taptech.doufu.bean.cartoon.PayCartoonGsonBean;
import com.taptech.doufu.bean.cartoon.WholeCartoonDetaisBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.ui.view.drawcircle.MyRecyclerView;
import com.taptech.doufu.event.BaseEventBusBean;
import com.taptech.doufu.event.EventBusCartoonCatlog;
import com.taptech.doufu.event.EventBusCollect;
import com.taptech.doufu.event.EventBusConstant;
import com.taptech.doufu.bean.ShareBeansInfo;
import com.taptech.doufu.bean.TipInfo;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.listener.ResultTipListener;
import com.taptech.doufu.services.history.ReadHistoryUtil;
import com.taptech.doufu.services.history.ReadRecord;
import com.taptech.doufu.db.history.Read_DataBaseUtil;
import com.taptech.doufu.db.history.Read_HirstoryUtil;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.services.CartoonServices;
import com.taptech.doufu.services.GiftService;
import com.taptech.doufu.services.PersonalNoteService;
import com.taptech.doufu.util.MobileState;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;
import com.taptech.doufu.util.NotifyUtil;
import com.taptech.doufu.ui.view.GiftDialogManager;
import com.taptech.doufu.ui.view.ShareTopPopupWindow;
import com.taptech.doufu.ui.view.TipDialog;
import com.taptech.doufu.ui.view.WaitDialog;
import com.taptech.doufu.weex.notification.QLXNotificationCenter;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liuwei on 16/6/14.
 */
public class CartoonScanNewActivity extends DiaobaoBaseActivity implements HttpResponseListener, View.OnClickListener {

    private static final String TAG = "CartoonScanNewActivity";
    public final static String SP_KEY_CARTOON_READ_HISTORY = "cartoon_read_history";
    //Views

    MyRecyclerView mRecyclerView;
    LinearLayoutManager layoutManager;
    LinearLayout bottomToolBarLayout;
    Window window;
    RelativeLayout cartoonMenuBtn, cartoonCommentBtn, topToolBarLayout, giveGiftBtn;
    TextView mobileStateTextView, commentNumTextView, topTitleTextView;
    ImageView backBtn, shareBtn, favBtn;
    WaitDialog mDialog;
    WholeCartoonDetailAdapter ada;

    WholeCartoonDetaisBean mCartoonDetailsBean;
    private String cartoonId = "";
    List<ImageBean> cartoonPicList;
    boolean isNetCallBackSuccess = false;//是否成功加载网络，如果正常加载才显示工具栏，用于adapter回调
    boolean isLoadNewestChapter = false;//是否加载最新章节：用于从首页漫画和漫画日历的跳转
    int loadBeginChapterPosInList = 0;//初始加载的章节列表，在图片list的位置
    int loadingChapterPos = 0;//当前显示的章节位置,最小值是1，所有进入值都要剪1
    boolean isToolBarLayoutVisitable = true;
    MobileState mobileState;//手机状态
    Read_HirstoryUtil readHirstoryUtil; //历史记录记录
    Read_DataBaseUtil read_dataBaseUtil; //浏览记录
    private List<String> mNovelIdList = new ArrayList<>();
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    boolean isFavorited = false;
    static final int LOGIN_REQUSET_CODE = 2001;//登录请求
    private int currIndex = 0;
    private boolean isPaying = false;
    private boolean isLogining = false;
    private RelativeLayout payDialogLayout;
    private TextView payCancelBtn;
    private TextView jumpToPayBtn;
    private TextView payDesContentText;
    private boolean hasMoney = true;

    public String getAutoPay() {
        return autoPay;
    }

    public void setAutoPay(String autoPay) {
        this.autoPay = autoPay;
    }

    private String autoPay = "0";
    private String currChapterId = "";
    private HashMap<String, Integer> chaptersMap = new HashMap<>();
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        window = getWindow();
        setContentView(R.layout.activity_cartoon_scannew_layout);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        addShadeBg();
        readHirstoryUtil = new Read_HirstoryUtil(this);
        read_dataBaseUtil = new Read_DataBaseUtil(this);
        findViews();
        initsDialog();
        initPayDialogView();
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            mCartoonDetailsBean = (WholeCartoonDetaisBean) intent.getSerializableExtra(Constant.DATA);
            isLoadNewestChapter = intent.getBooleanExtra(Constant.IS_NEWSTCARTOON, false);
            cartoonId = intent.getStringExtra(Constant.CARTOON_ID);
            if (!isLoadNewestChapter) {
                loadingChapterPos = intent.getIntExtra(Constant.POSITION, 0);
                if (loadingChapterPos <= 0) {
                    loadingChapterPos = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SP_KEY_CARTOON_READ_HISTORY+cartoonId,this,0);
                }
            }
        }
        if (mCartoonDetailsBean != null && mCartoonDetailsBean.getDetail()!=null) {//本地数据
            cartoonId = mCartoonDetailsBean.getDetail().getId();
            handleHttpResponse();
            dismissDialog();
        }else{
            if (!TextUtils.isEmpty(cartoonId)) {
                //加载漫画详情
                getData(cartoonId);
            }
        }
        getReadTicket();
        setCollect();
    }
    private void setCollect() {
        //加载自己是否收藏过接口
        if (AccountService.getInstance().isLogin()) {
            if (!TextUtils.isEmpty(cartoonId)) {
                ApiClient.getInstance().setUseCache(false).getService().judgeCollectExist(cartoonId,String.valueOf(Constant.OBJECT_TYPE_CARTOON))
                        .compose(RxJavaHelper.<CollectExistGsonBean>observeOnMainThread(this))
                        .subscribe(new BaseSubscriber<CollectExistGsonBean>(){
                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                            }

                            @Override
                            public void onNext(CollectExistGsonBean collectExistGsonBean) {
                                super.onNext(collectExistGsonBean);
                                if (collectExistGsonBean != null
                                        && collectExistGsonBean.getStatus() == Constant.STATUS_SUCCESS
                                        && collectExistGsonBean.getData() != null) {
                                    changeFavoriteUi(collectExistGsonBean.getData().isHas_fav());
                                }
                            }
                        });
            }
        }
    }

    private void getData(String id) {
        ApiClient.getInstance().getService().getCartoonAllDetail(id)
                .compose(RxJavaHelper.<CartoonDetailGsonBean>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<CartoonDetailGsonBean>(){
                    @Override
                    public void onNext(CartoonDetailGsonBean bean) {
                        super.onNext(bean);
                        if (bean != null
                                && bean.getStatus() == Constant.STATUS_SUCCESS
                                && bean.getData()!=null) {
                            mCartoonDetailsBean = bean.getData();
                            handleHttpResponse();
                            cancelReadMark(cartoonId);
                        }else{
                            Toast.makeText(CartoonScanNewActivity.this, "数据获取失败", Toast.LENGTH_LONG).show();
                        }
                        dismissDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        try {
                            dismissDialog();
                            Toast.makeText(CartoonScanNewActivity.this, "网络异常，请检查网络后再试", Toast.LENGTH_LONG).show();
                        } catch (Exception e1) {

                        }
                    }
                });
    }


    public CartoonReadTicketBean.ReadTicketInfo readTicketInfo;

    public void getReadTicket() {
        ApiClient.getInstance().getService().getCartoonReadTicket(cartoonId)
                .compose(RxJavaHelper.<CartoonReadTicketGsonBean>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<CartoonReadTicketGsonBean>(){
                    @Override
                    public void onNext(CartoonReadTicketGsonBean cartoonReadTicketGsonBean) {
                        super.onNext(cartoonReadTicketGsonBean);
                        if (cartoonReadTicketGsonBean != null && cartoonReadTicketGsonBean.getData()!=null) {
                            readTicketInfo = cartoonReadTicketGsonBean.getData().getReadTicketInfo();
                            //刷新所有支付页面
                            if (ada != null) {
                                ada.notifyDataSetChanged();
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    private void dismissDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    /**
     * 缺钱弹窗初始化
     */
    private void initPayDialogView(){
        payDialogLayout = (RelativeLayout) findViewById(R.id.pay_dialog_layout);
        payCancelBtn = (TextView) findViewById(R.id.pay_cancel_btn);
        jumpToPayBtn = (TextView) findViewById(R.id.jump_to_pay_btn);
        payDesContentText = (TextView) findViewById(R.id.text_des_content);
        payCancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (payDialogLayout.isShown()){
                    payDialogLayout.setVisibility(View.GONE);
                }
            }
        });
        jumpToPayBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (payDialogLayout.isShown()){
                    payDialogLayout.setVisibility(View.GONE);
                }
                GiftService.enterPayWebActivity(CartoonScanNewActivity.this);
            }
        });
    }

    private void findViews() {
        //布局相关
        cartoonMenuBtn = (RelativeLayout) findViewById(R.id.cartoon_menu_btn);
        cartoonCommentBtn = (RelativeLayout) findViewById(R.id.cartoon_comment_btn);
        giveGiftBtn = (RelativeLayout) findViewById(R.id.cartoon_gift_btn);
        backBtn = (ImageView) findViewById(R.id.back_btn);
        shareBtn = (ImageView) findViewById(R.id.share_cartoon_btn);
        favBtn = (ImageView) findViewById(R.id.fav_cartoonn_btn);
        mobileStateTextView = (TextView) findViewById(R.id.mobile_state_layout);
        commentNumTextView = (TextView) findViewById(R.id.comment_num_textview);

        bottomToolBarLayout = (LinearLayout) findViewById(R.id.bottom_tool_bar_layout);
        topToolBarLayout = (RelativeLayout) findViewById(R.id.top_tool_bar_layout);
        topTitleTextView = (TextView) findViewById(R.id.cartoon_title_textview);
        mRecyclerView = (MyRecyclerView) findViewById(R.id.recycle_cartoon_scannew);
//        layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
        layoutManager = new LinearLayoutManager(this);
//        layoutManager.setInitialItemPrefetchCount(3);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                    if (isToolBarLayoutVisitable) {
                        handleToolbarLayoutDisplay(false);
                    }
                }
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }


    @Override
    public void finish() {

        if (isMustClose|| isWebView) {
            super.finish();
        }else{
            if (!isFavorited && AccountService.getInstance().isLogin()) {
                showTipDialog();
            } else {
                super.finish();
            }
        }
    }

    private void showTipDialog() {
        TipInfo info = new TipInfo();
        info.setTitle("收藏作品");
        info.setTipContent("喜欢这部作品就收藏它吧~");
        info.setTipListener(tipListener);
        TipDialog dialog = new TipDialog(this, R.style.updateDialog, info);
        dialog.show();
    }

    private boolean isMustClose = false;
    private ResultTipListener tipListener = new ResultTipListener() {
        @Override
        public void resultBack(int flag, int type)
        {
            // TODO Auto-generated method stub
            isMustClose = true;
            if (flag == 1) { //确定
                isNumChange = true;
                changeIsFavoritedState();
            }else{
                finish();
            }
        }
    };


    @Override
    protected void onPause() {
        try {
            DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SP_KEY_CARTOON_READ_HISTORY+cartoonId,(1 + loadingChapterPos),this);
            // 记录浏览记录
            Map<String, String> record = readHirstoryUtil.queryCartoonHirstory(cartoonId);
            if (record != null && record.size() > 0) {
                readHirstoryUtil.updateCartoonHirstory(cartoonId, (1 + loadingChapterPos) + "");
            } else {
                readHirstoryUtil.insertCartoonHirstory(cartoonId, (1 + loadingChapterPos) + "");
            }

            //记录详细的浏览记录
            mNovelIdList = read_dataBaseUtil.queryNovelId();
            if (mNovelIdList == null) {
                return;
            }
            if (mNovelIdList.contains(cartoonId)) {
                read_dataBaseUtil.update(cartoonId, "", 1 + loadingChapterPos, mCartoonDetailsBean.getIds().size(), mCartoonDetailsBean.getDetail().getTitle(), getTimeBySystem(), mCartoonDetailsBean.getDetail().getImage(),Constant.OBJECT_TYPE_CARTOON);
            } else {
                read_dataBaseUtil.insert(cartoonId, "", 1 + loadingChapterPos, mCartoonDetailsBean.getIds().size(), mCartoonDetailsBean.getDetail().getTitle(), getTimeBySystem(), mCartoonDetailsBean.getDetail().getImage(),Constant.OBJECT_TYPE_CARTOON);
            }

            ReadRecord readRecord = new ReadRecord();
            readRecord.setType(Constant.OBJECT_TYPE_CARTOON);
            readRecord.setSection_id("");
            readRecord.setNovel_id(cartoonId);
            readRecord.setPosition(1 + loadingChapterPos);
            readRecord.setAll_num( mCartoonDetailsBean.getIds().size());
            readRecord.setTime(getTimeBySystem());
            readRecord.setName(mCartoonDetailsBean.getDetail().getTitle());
            readRecord.setImg_url(mCartoonDetailsBean.getDetail().getImage());
            ReadHistoryUtil.addOrUpdateData(readRecord);

            NotifyUtil.refreshCollectCellNotify(cartoonId,"",1 + loadingChapterPos);

            BaseEventBusBean eventBus = new BaseEventBusBean();
            eventBus.setTag(EventBusConstant.TAG_BOOK_SHELF);
            EventBus.getDefault().post(eventBus);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onPause();
    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        try {
            if (response.getStatus() == Constant.STATUS_SUCCESS) {
                switch (handleType) {
                    case CartoonServices.HANDLE_TYPE_LOAD_CARTOON_DETAIL2:
                        mCartoonDetailsBean = JSON.parseObject(response.getData().toString(), WholeCartoonDetaisBean.class);
                        handleHttpResponse();
                        dismissDialog();
                        break;
                    case PersonalNoteService.HANDLE_TYPE_JUDGE_COLLECTION_EXIST:
                        try {
                            JSONObject data = (JSONObject) response.getData();
                            changeFavoriteUi(data.getBoolean("has_fav"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        break;
                    case PersonalNoteService.HANDLE_TYPE_ADD_COLLECT:
                        changeFavoriteUi(true);
                        UIUtil.toastMessage(CartoonScanNewActivity.this, "收藏成功");
                        dismissDialog();
                        if (isMustClose) {
                            finish();
                        }
                        break;
                    case PersonalNoteService.HANDLE_TYPE_REMOVE_COLLECT:
                        changeFavoriteUi(false);
                        UIUtil.toastMessage(CartoonScanNewActivity.this, "已取消收藏");
                        dismissDialog();
                        break;
                    case CartoonServices.HANDLE_TYPE_PAY_CARTOON:
                        PayCartoonBean bean = JSON.parseObject(response.getData().toString(), PayCartoonBean.class);
                        handlePayData(bean);
                        dismissDialog();
                        break;
                }
            } else
            {
                Toast.makeText(CartoonScanNewActivity.this, "网络异常，请检查网络后再试", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e)
        {
            Toast.makeText(CartoonScanNewActivity.this, "网络异常，请检查网络后再试", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    private void handlePayData(PayCartoonBean bean) {
        if (bean != null && bean.isPaid()) {
            hasMoney = true;
            PayCartoonBean.Chapter info = bean.getChapter();
            if (info != null && info.getImages()!=null &&
                    cartoonPicList != null && cartoonPicList.size() > currIndex) {
                cartoonPicList.remove(currIndex);
                cartoonPicList.addAll(currIndex, info.getImages());
                ada.refrushList(cartoonPicList);
                mRecyclerView.scrollToPosition(currIndex);

            }
        }else{
            if ("30501".equals(bean.getCode())) {
                if(!"1".equals(autoPay)){
                    payDialogLayout.setVisibility(View.VISIBLE);
                    payDesContentText.setText(bean.getMsg());
                }else{
                    if(ada!=null){
                        ada.notifyItemChanged(currIndex);
                    }
                    autoPay = "0";
                    hasMoney = false;
                }
            } else if ("30804".equals(bean.getCode())) {
                Toast.makeText(this, bean.getMsg(), Toast.LENGTH_LONG).show();
                getReadTicket();
            } else {
                if (!isPaying) {
                    Toast.makeText(this, bean.getMsg(), Toast.LENGTH_LONG).show();
                }
            }
        }
        isPaying = false;
    }

    private boolean isWebView = false;
    //设置网络请求返回值，做数据处理工作
    private void handleHttpResponse()
    {
        if (mCartoonDetailsBean != null) {
            if (mCartoonDetailsBean.detail != null) {
                autoPay = mCartoonDetailsBean.detail.getAuto_pay();
            }
            if (mCartoonDetailsBean.detail!=null &&
                    "1".equals(mCartoonDetailsBean.detail.getOrigin())) { //有妖气漫画
                loadYouYaoQi();
            }else{
                //加载漫画
                showCartoonInfo();
                //加载状态栏目
                initToolLayout();
            }
        }
    }

    private void loadYouYaoQi() {
        List<CartoonSectionInfo> dataList = mCartoonDetailsBean.getSection_info();
        if (AccountService.getInstance().isLogin()) {
            if (dataList != null && dataList.size() > 0) {
                Intent intent = new Intent();
                intent.setClass(this, BrowseActivity.class);
                int index = 0;
                if (mCartoonDetailsBean.getRead_status() != null &&
                        dataList.size()>mCartoonDetailsBean.getRead_status().getIndex()) {
                    index = mCartoonDetailsBean.getRead_status().getIndex();
                }
                intent.putExtra(Constant.URL, dataList.get(index).getChapter_url());
                intent.putExtra(Constant.TITLE, dataList.get(index).getTitle());
                intent.putExtra(Constant.JS_URL, mCartoonDetailsBean.getJs_url());
                startActivity(intent);
                enterAnimAlpha(this);
            }
        } else {
            AccountService.getInstance().jumpToLogin();
            enterAnimAlpha(this);
        }
        isWebView = true;
    }

    public interface OnPayPageListen {
        void onClick(ImageBean bean, boolean isAuto,int index);
        void onPageChange(ImageBean bean,int index);
        void onClickPage();
        void onJumpLogin(int position);
    }

    public interface OnImageListen{
        void onItemChange(ImageBean bean,int index);
        void onItemClick(ImageBean bean);
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        if(isWebView){
            finish();
            return;
        }
        if(isLogining){
            isLogining = false;
            if (AccountService.getInstance().isLogin()) {
                if (mDialog != null) {
                    mDialog.show();
                }
                if (!TextUtils.isEmpty(cartoonId)) {
                    getData(cartoonId);
                }
            }
        }
    }

    //显示具体的漫画
    private void showCartoonInfo() {
        try {
            //拆分漫画数据
            if (cartoonPicList != null) {
                cartoonPicList.clear();
            } else {
                cartoonPicList = new ArrayList<>();
            }
            if (isLoadNewestChapter) {
                //加载最新章节
                for (int i = 0; i < mCartoonDetailsBean.section_info.size(); i++) {
                    CartoonSectionInfo sectionInfo = mCartoonDetailsBean.section_info.get(i);
                    if (sectionInfo != null) {
                        chaptersMap.put(sectionInfo.getId(), i);
                        if (i == (mCartoonDetailsBean.section_info.size() - 1)){
                            loadBeginChapterPosInList = cartoonPicList.size();
                            loadingChapterPos = i;
                            currChapterId = sectionInfo.getId();
                            statRead(currChapterId);
                        }
                        if(sectionInfo.isNeed_pay()){
                            ImageBean bean = new ImageBean();
                            bean.setNeed_pay(true);
                            bean.setTitle(sectionInfo.getTitle());
                            bean.setPrice(sectionInfo.getPrice());
                            bean.setOriginal_price(sectionInfo.getOriginal_price());
                            bean.setChapter_id(sectionInfo.getId());
                            bean.setChapterPosInList(i);
                            cartoonPicList.add(bean);
                        }else{
                            if (sectionInfo.getImages() != null) {
                                for (int j = 0; j < sectionInfo.getImages().size(); j++) {
                                    sectionInfo.getImages().get(j).setChapterPosInList(i);
                                    sectionInfo.getImages().get(j).setChapter_id(sectionInfo.getId());
                                    cartoonPicList.add(sectionInfo.getImages().get(j));
                                }
                            }
                        }
                    }

                }
            } else {
                //根据历史记录加载
                for (int i = 0; i < mCartoonDetailsBean.section_info.size(); i++) {
                    CartoonSectionInfo sectionInfo = mCartoonDetailsBean.section_info.get(i);
                    if (sectionInfo != null) {
                        chaptersMap.put(sectionInfo.getId(), i);
                        if (i == loadingChapterPos - 1) {
                            loadBeginChapterPosInList = cartoonPicList.size();
                            loadingChapterPos = loadingChapterPos - 1;
                            currChapterId = sectionInfo.getId();
                            statRead(currChapterId);
                        }
                        if(sectionInfo.isNeed_pay()){
                            ImageBean bean = new ImageBean();
                            bean.setNeed_pay(true);
                            bean.setTitle(sectionInfo.getTitle());
                            bean.setPrice(sectionInfo.getPrice());
                            bean.setOriginal_price(sectionInfo.getOriginal_price());
                            bean.setChapterPosInList(i);
                            bean.setChapter_id(sectionInfo.getId());
                            cartoonPicList.add(bean);
                        }else{
                            if (sectionInfo.getImages() != null) {
                                for (int j = 0; j < sectionInfo.getImages().size(); j++) {
                                    sectionInfo.getImages().get(j).setChapterPosInList(i);
                                    sectionInfo.getImages().get(j).setChapter_id(sectionInfo.getId());
                                    cartoonPicList.add(sectionInfo.getImages().get(j));
                                }
                            }
                        }
                    }
                }
            }

            if(ada!=null){
                ada.refrushList(cartoonPicList);
            }else{
                ada = new WholeCartoonDetailAdapter(CartoonScanNewActivity.this, cartoonPicList,new OnPayPageListen(){
                    @Override
                    public void onClick(ImageBean bean, boolean isAuto,int index) {
                        currIndex = index;
                        mDialog.show();
                        if (isAuto && hasMoney) {
                            autoPay = "1";
                        }
                        payCartoon(bean.getChapter_id(), isAuto,bean.getPrice());
                    }

                    @Override
                    public void onPageChange(ImageBean bean, int index) {
                        if("1".equals(autoPay) && AccountService.getInstance().isLogin() && !isPaying && hasMoney){
                            isPaying = true;
                            currIndex = index;
                            mDialog.show();
                            payCartoon(bean.getChapter_id(), false,bean.getPrice());
                        }
                        changeChapter(bean.getChapter_id());
                    }

                    @Override
                    public void onClickPage() {
                        setToolBarLayout();
                    }

                    @Override
                    public void onJumpLogin(int position) {
                        isLogining = true;
                        loadingChapterPos = position + 1;
                    }
                },new OnImageListen(){

                    @Override
                    public void onItemChange(ImageBean bean, int index) {
                        if (bean == null) {
                            return;
                        }

                        String chapterId = bean.getChapter_id();
                        if (!TextUtils.isEmpty(chapterId) && !chapterId.equals(currChapterId)) {
                            currChapterId = chapterId;
                            statRead(chapterId);
                            changeChapter(chapterId);
                        }
                    }

                    @Override
                    public void onItemClick(ImageBean bean) {
                        setToolBarLayout();
                    }
                });
                mRecyclerView.setAdapter(ada);
            }
            mRecyclerView.scrollToPosition(loadBeginChapterPosInList);
            isNetCallBackSuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void statRead(String id){
        ApiClient.getInstance().getService().statRead(id)
                .compose(RxJavaHelper.<ResponseBaseBean>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<ResponseBaseBean>(){
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onNext(ResponseBaseBean responseBaseBean) {
                        super.onNext(responseBaseBean);
                    }
                });
    }

    private void cancelReadMark(String id){
        ApiClient.getInstance().getService().cancelReadMark(id,Constant.OBJECT_TYPE_CARTOON)
                .compose(RxJavaHelper.<ResponseBaseBean>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<ResponseBaseBean>(){
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onNext(ResponseBaseBean responseBaseBean) {
                        super.onNext(responseBaseBean);
                    }
                });
    }

    private void payCartoon(String chapterId, boolean isAutoPay,final String price) {
        int flag = 0;
        if (isAutoPay) {
            flag = 1;
        }
        String ticketId = "";
        if (readTicketInfo != null && readTicketInfo.getId() > 0) {
            ticketId = String.valueOf(readTicketInfo.getId());
            QLXNotificationCenter.getInstance().postNotify("TFMyTicketNumChangeNotify",null);
        }
        ApiClient.getInstance().getService().payCartoon(cartoonId, chapterId, String.valueOf(flag),ticketId)
                .compose(RxJavaHelper.<PayCartoonGsonBean>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<PayCartoonGsonBean>(){
                    @Override
                    public void onNext(PayCartoonGsonBean payCartoonGsonBean) {
                        super.onNext(payCartoonGsonBean);
                        if (payCartoonGsonBean != null
                                && payCartoonGsonBean.getStatus() == Constant.STATUS_SUCCESS
                                && payCartoonGsonBean.getData() != null) {
                            if (!TextUtils.isEmpty(payCartoonGsonBean.getData().getTipinfo())) {
                                Toast.makeText(CartoonScanNewActivity.this, payCartoonGsonBean.getData().getTipinfo(), Toast.LENGTH_LONG).show();
                            }
                            if (readTicketInfo != null && readTicketInfo.getId() > 0) {
                                getReadTicket();
                            }
                            handlePayData(payCartoonGsonBean.getData());
                            EventBusCartoonCatlog catlog = new EventBusCartoonCatlog();
                            catlog.setTag(EventBusCartoonCatlog.tag);
                            EventBus.getDefault().post(catlog);

                        }else{
                            Toast.makeText(CartoonScanNewActivity.this, "数据获取失败", Toast.LENGTH_LONG).show();
                        }
                        dismissDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        try {
                            Toast.makeText(CartoonScanNewActivity.this, "网络异常，请检查网络后再试", Toast.LENGTH_LONG).show();
                            dismissDialog();
                        } catch (Exception e1) {

                        }
                    }
                });
    }

    private void changeChapter(String chapterId) {
        try {
            loadingChapterPos = chaptersMap.get(chapterId);
            getMobileSateStr(mobileState);
            topTitleTextView.setText(mCartoonDetailsBean.section_info.get(loadingChapterPos).getTitle());
            commentNumTextView.setText(mCartoonDetailsBean.section_info.get(loadingChapterPos).getComment_times());
        } catch (Exception e) {

        }
    }

    private void setToolBarLayout() {
        if (isToolBarLayoutVisitable) {
            handleToolbarLayoutDisplay(false);
        } else {
            handleToolbarLayoutDisplay(true);
        }
    }

    private void handleToolbarLayoutDisplay(boolean isVisiable)
    {
        if (isVisiable != isToolBarLayoutVisitable)
        {
            // 0是底部框，1是顶部框
            ObjectAnimator[] objectAnimators = new ObjectAnimator[2];
            AnimatorSet animatorSet = new AnimatorSet();
            // 出现
            if (isVisiable)
            {
                objectAnimators[0] = ObjectAnimator.ofFloat(bottomToolBarLayout, "translationY", ScreenUtil.getScreenHeight(this), 0);
                objectAnimators[1] = ObjectAnimator.ofFloat(topToolBarLayout, "translationY", -topToolBarLayout.getMeasuredHeight(), 0);
                window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
            // 隐藏
            else
            {
                objectAnimators[0] = ObjectAnimator.ofFloat(bottomToolBarLayout, "translationY", 0, ScreenUtil.getScreenHeight(this) - bottomToolBarLayout.getMeasuredHeight());
                objectAnimators[1] = ObjectAnimator.ofFloat(topToolBarLayout, "translationY", 0, -topToolBarLayout.getMeasuredHeight());
                window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
            animatorSet.setDuration(500);
            animatorSet.playTogether(objectAnimators);
            animatorSet.start();
            isToolBarLayoutVisitable = isVisiable;
        }
    }

    private void initToolLayout()
    {
        cartoonMenuBtn.setOnClickListener(this);
        cartoonCommentBtn.setOnClickListener(this);
        giveGiftBtn.setOnClickListener(this);
        if (mCartoonDetailsBean.detail.getTransfered() != null && mCartoonDetailsBean.detail.getTransfered().equals("0"))
        {
            giveGiftBtn.setVisibility(View.VISIBLE);
        } else
        {
            giveGiftBtn.setVisibility(View.GONE);
        }
        backBtn.setOnClickListener(this);
        shareBtn.setOnClickListener(this);
        favBtn.setOnClickListener(this);
        mobileState = MobileState.getInstance();
        mobileState.initListenMobileState(new MobileState.StateChangeListener()
        {
            @Override
            public void onStateChanged()
            {
                getMobileSateStr(mobileState);
            }
        });
        getMobileSateStr(mobileState);
        commentNumTextView.setText(mCartoonDetailsBean.detail.getComment_times());
    }

    /**
     * 显示手机状态和当前页
     *
     * @param mobileState
     */
    private void getMobileSateStr(MobileState mobileState)
    {
        if (mobileState == null)
        {
            return;
        }
        String stateStr = null;
        StringBuilder sb = new StringBuilder();
        sb.append(" ");
        sb.append(String.valueOf(loadingChapterPos+1));
        sb.append("/");
        if (mCartoonDetailsBean.ids != null)
        {
            sb.append(mCartoonDetailsBean.ids.size());
        }
        sb.append(" ");

        sb.append(mobileState.systemTime);

        int netType = mobileState.netWorkState;
        switch (netType)
        {
            case ConnectivityManager.TYPE_MOBILE:
                sb.append(" 移动网络 ");
                break;
            case ConnectivityManager.TYPE_WIFI:
                sb.append(" WIFI ");
                break;
        }
        sb.append("电量:");
        sb.append(String.valueOf(mobileState.battery));
        sb.append("% ");
        stateStr = sb.toString();
        if (stateStr != null)
        {
            mobileStateTextView.setText(stateStr);
        }

        if (topTitleTextView != null && mCartoonDetailsBean != null)
        {
            if ((mCartoonDetailsBean.getSection_info() != null) && (mCartoonDetailsBean.getSection_info().size() > loadingChapterPos))
            {
                topTitleTextView.setText(mCartoonDetailsBean.section_info.get(loadingChapterPos).getTitle());
            }
        }
    }

    private void initsDialog()
    {
        mDialog = new WaitDialog(this, R.style.loadNovelDialog, "");
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.show();
    }

    @Override
    public void onClick(View v)
    {
        Map keyMap = new HashMap();
        if (!TextUtils.isEmpty(cartoonId))
        {
            keyMap.put("mId", cartoonId);
            keyMap.put("mpos", loadingChapterPos);
        }
        switch (v.getId())
        {
            case R.id.cartoon_menu_btn:
                TMAnalysis.event(this, "cartoon_scan_menu", keyMap);
                CartoonServices.enterCartoonEpisodeMenu(this, mCartoonDetailsBean);
                break;
            case R.id.cartoon_comment_btn:
                TMAnalysis.event(this, "cartoon_scan_comment", keyMap);
                HashMap<String, String> data = new HashMap<>();
                data.put("id", cartoonId);
                data.put("segment_index", "0");
                try {
                    String articleId = mCartoonDetailsBean.section_info.get(loadingChapterPos).getId();
                    data.put("cur_article_id", articleId);
                } catch (Exception e) {

                }
                SimpleWeexActivity.startActivity(this,"TFComicComment/TFComment.js",data);
                break;
            case R.id.back_btn:
                finish();
                break;
            case R.id.share_cartoon_btn:
                TMAnalysis.event(this, "cartoon_scan_share", keyMap);
                topShare(v);
                break;
            case R.id.cartoon_gift_btn:
                TMAnalysis.event(this, "give_gift_in_cartoon", keyMap);
                CartoonBean bean = loadOriginalBean();
                bean.setId(cartoonId);
                GiftDialogManager.getInstance(this, bean);
                break;
            case R.id.fav_cartoonn_btn:
                TMAnalysis.event(this, "collection_in_cartoon", keyMap);
                isNumChange = true;
                changeIsFavoritedState();
                break;
        }
    }

    private CartoonBean loadOriginalBean()
    {
        CartoonBean bean = new CartoonBean();
        if ((mCartoonDetailsBean != null) && (mCartoonDetailsBean.section_info != null))
        {
            bean.setTitle(mCartoonDetailsBean.detail.getTitle());
            CartoonSectionInfo[] infos = new CartoonSectionInfo[mCartoonDetailsBean.getSection_info().size()];
            for (int i = 0; i < mCartoonDetailsBean.getSection_info().size(); i++)
            {
                CartoonSectionInfo infoSingle = new CartoonSectionInfo();
                infoSingle.setTitle(mCartoonDetailsBean.section_info.get(i).getTitle());
                infoSingle.setTitle2(mCartoonDetailsBean.section_info.get(i).getTitle2());
                infoSingle.setId(mCartoonDetailsBean.section_info.get(i).getId());
                infoSingle.setRead_times(mCartoonDetailsBean.section_info.get(i).getRead_times());
                infos[i] = infoSingle;
            }
            bean.setSection_info(infos);
            bean.setUser(mCartoonDetailsBean.getDetail().getUser());
            bean.setObject_type(mCartoonDetailsBean.getDetail().getObject_type());
        }
        return bean;
    }

    // 分享
    // 顶部分享
    private void topShare(View view) {
        ShareTopPopupWindow menuWindow = new ShareTopPopupWindow(this);
        CartoonDetail bean;
        if (mCartoonDetailsBean == null)
        {
            return;
        } else
        {
            bean = mCartoonDetailsBean.detail;
            if (bean == null)
            {
                return;
            }
        }

        ShareBeansInfo shareInfo = new ShareBeansInfo(bean.getId(), bean.getTitle(), bean.getImage(), bean.getShare_url(), ShareBeansInfo.CARTOON_SHARE_FLAG);
        shareInfo.setDescription(bean.getIntro());
        HomeTopBean homeTopBean = new HomeTopBean();
        if (bean.getUser() != null)
        {
            homeTopBean = new HomeTopBean();
            homeTopBean.setAuthor(bean.getUser().getName());
        }
        shareInfo.setShareData(homeTopBean);

        String[] tagStrings = bean.getTag_list().split("\\s+");
        if (tagStrings != null && tagStrings.length > 0)
        {
            shareInfo.setTags(tagStrings);
        }
        menuWindow.setShareBeans(shareInfo);
        menuWindow.showAsDropDown(view, 0, 0); // 设置layout在PopupWindow中显示的位置
    }

    private void changeIsFavoritedState() {
        if (!TextUtils.isEmpty(cartoonId)) {
            if (AccountService.getInstance().isLogin()) {
                if (mDialog != null) {
                    mDialog.show();
                }
                if (isFavorited) {
                    removeCollect();
                } else {
                    addCollect();
                }
            } else {
                AccountService.getInstance().jumpToLogin();
            }
        }
    }

    /**
     * 收藏
     */
    private void addCollect() {
        ApiClient.getInstance().setUseCache(false).getService().addCollect(cartoonId,String.valueOf(Constant.OBJECT_TYPE_CARTOON))
                .compose(RxJavaHelper.<ResponseBaseBean>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<ResponseBaseBean>(){
                    @Override
                    public void onNext(ResponseBaseBean responseBaseBean) {
                        super.onNext(responseBaseBean);
                        if (responseBaseBean != null && responseBaseBean.getStatus() == Constant.STATUS_SUCCESS) {
                            changeFavoriteUi(true);
                            NotifyUtil.collectStatusChange(cartoonId,Constant.OBJECT_TYPE_CARTOON,true);
                            UIUtil.toastMessage(CartoonScanNewActivity.this, "收藏成功");
                            dismissDialog();
                            if (isMustClose) {
                                finish();
                            }
                        }else{
                            Toast.makeText(CartoonScanNewActivity.this,"操作失败，请重试",Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Toast.makeText(CartoonScanNewActivity.this,"操作失败，请重试",Toast.LENGTH_LONG).show();
                    }
                });
    }

    /**
     * 取消收藏
     */
    private void removeCollect() {
        ApiClient.getInstance().getService().removeCollect(cartoonId,String.valueOf(Constant.OBJECT_TYPE_CARTOON))
                .compose(RxJavaHelper.<ResponseBaseBean>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<ResponseBaseBean>(){
                    @Override
                    public void onNext(ResponseBaseBean responseBaseBean) {
                        super.onNext(responseBaseBean);
                        if (responseBaseBean != null && responseBaseBean.getStatus() == Constant.STATUS_SUCCESS) {
                            changeFavoriteUi(false);
                            NotifyUtil.collectStatusChange(cartoonId,Constant.OBJECT_TYPE_CARTOON,true);
                            UIUtil.toastMessage(CartoonScanNewActivity.this, "已取消收藏");
                            dismissDialog();
                        }else{
                            Toast.makeText(CartoonScanNewActivity.this,"操作失败，请重试",Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Toast.makeText(CartoonScanNewActivity.this,"操作失败，请重试",Toast.LENGTH_LONG).show();
                    }
                });
    }

    boolean isNumChange = false;

    private void changeFavoriteUi(boolean isFavorited) {
        if (isNumChange) {
            EventBusCollect event = new EventBusCollect();
            event.setTag(EventBusCollect.tag);
            event.setHasCollect(isFavorited);
            EventBus.getDefault().post(event);
            isNumChange = false;
        }

        if (isFavorited) {
            favBtn.setImageResource(R.drawable.novel_des_fav_select2);
            this.isFavorited = isFavorited;
        } else {
            favBtn.setImageResource(R.drawable.novel_des_fav_default2);
        }
        this.isFavorited = isFavorited;
    }

    private String getTimeBySystem() {
        String dateStr = dateFormat.format(new Date());// 可以将时间保存起来
        return dateStr;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mobileState != null){
            mobileState.destoryListner();
        }
    }
}
